﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Media;
using System.Net;
using System.Text;
using System.Threading;
using System.Web;

namespace Google.Translates.Core
{
    public class SpeechByBingHttp
    {
        public const int MP3_Bit = 24;

        protected string m_AppId;

        public SpeechByBingHttp()
        {
            m_AppId = ApiSetting.GetBingTranslateAppId();
        }

        public void SpeakSentence(string textVal, string trgLangKey)
        {
            var sbUrl =
                new StringBuilder("http://api.microsofttranslator.com/v2/Http.svc/Speak?appid=" + m_AppId);
            sbUrl.Append("&language=en&format=" + HttpUtility.UrlEncode("audio/wav") + "&options=MaxQuality");
            sbUrl.Append("&text=" + HttpUtility.UrlEncode(textVal));
            WebRequest webRequest = WebRequest.Create(sbUrl.ToString());
            WebResponse response = null;
            try
            {
                response = webRequest.GetResponse();
                using (Stream stream = response.GetResponseStream())
                {
                    using (var player = new SoundPlayer(stream))
                    {
                        player.PlaySync();
                    }
                }
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                    response = null;
                }
            }
        }

        public string SaveSpeechFiles(string longSentence, string trgLangKey, string saveDirPath,
                                      ref StringCollection fileNames)
        {
            var sb = new StringBuilder();
            var splitKeyVals = new List<string>();
            List<string> shotSectences = StringHelper.SplitSentence(longSentence, ref splitKeyVals);
            int amount = 1;
            for (int i = 0; i < shotSectences.Count; i++)
            {
                string srcSentence = shotSectences[i];
                if (srcSentence.Length == 0) continue;
                if ((amount) % 1 == 0)
                    Thread.Sleep(200);
                string eachReVal = SaveSpeechFile(srcSentence, trgLangKey, saveDirPath, ref fileNames);
                sb.Append(eachReVal);
                sb.Append("<br>");
                amount++;
            }
            return sb.ToString();
        }


        public string SaveSpeechFile(string queryVal, string langKey, string saveDirPath, ref StringCollection fileNames)
        {
            string strMsg = "";
            if (string.IsNullOrEmpty(queryVal.Trim())) return strMsg;
            var sbUrl =
                new StringBuilder("http://api.microsofttranslator.com/v2/Http.svc/Speak?appid=" + m_AppId);
            if (!string.IsNullOrEmpty(langKey)) sbUrl.Append("&language=" + langKey);
            sbUrl.Append("&format=" + HttpUtility.UrlEncode("audio/mp3") + "&options=MaxQuality");
            sbUrl.Append("&text=" + HttpUtility.UrlEncode(queryVal));
            var innerRequest = (HttpWebRequest) WebRequest.Create(sbUrl.ToString());
            var innerResponse = (HttpWebResponse) innerRequest.GetResponse();
            Stream rStream = innerResponse.GetResponseStream();
            BinaryReader bReader = null;
            FileStream fsWriter = null;
            BinaryWriter bWriter = null;
            if (fileNames == null) fileNames = new StringCollection();
            string eachSpeechFileName = MP3_Bit + "_" + fileNames.Count.ToString().PadLeft(8, '0') + ".mp3";
            string speechFilePath = saveDirPath + (saveDirPath.EndsWith("\\") ? "" : "\\") + eachSpeechFileName;
            string txtFilePath = speechFilePath.Substring(0, speechFilePath.Length - 4) + ".txt";
            if (!Directory.Exists(saveDirPath)) Directory.CreateDirectory(saveDirPath);
            var sw = new StreamWriter(txtFilePath, false, Encoding.UTF8);
            try
            {
                if (rStream != null)
                {
                    bReader = new BinaryReader(rStream);
                    if (File.Exists(speechFilePath))
                        File.Delete(speechFilePath);
                    fsWriter = new FileStream(speechFilePath, FileMode.CreateNew);
                    bWriter = new BinaryWriter(fsWriter);

                    Byte[] r = bReader.ReadBytes(100000); //1K的缓存

                    while (r.Length > 0)
                    {
                        bWriter.Write(r);
                        r = bReader.ReadBytes(100000);
                    }

                    fileNames.Add(eachSpeechFileName);
                    sw.WriteLine(HttpUtility.UrlEncode(queryVal));
                    strMsg = "Save file to [" + speechFilePath + "]";
                }
            }
            finally
            {
                sw.Dispose();
                sw.Close();
                if (bWriter != null)
                {
                    bWriter.Close();
                }
                if (fsWriter != null)
                {
                    fsWriter.Dispose();
                    fsWriter.Close();
                }
                if (bReader != null) bReader.Close();
                if (rStream != null)
                {
                    rStream.Dispose();
                    rStream.Close();
                }
                innerResponse.Close();
            }
            return strMsg;
        }
    }
}